
#include <stdio.h>      // 提供 printf 函数
#include <string.h>     // 提供 strlen 和 memcmp 函数
#include <stdint.h>     // 提供 uint8_t, uint32_t 等标准类型

// 包含 openHiTLS Base64 库的公共头文件，这是调用其功能的唯一入口
#include "bsl/bsl_base64.h"

int main()
{
    // 1. 准备要编码的原始数据
    const uint8_t original_data[] = "wuningxi";
    uint32_t original_len = strlen((const char *)original_data);

    printf("================ Base64 Encode/Decode Final Test ================\n");
    printf("Original Data: \"%s\"\n", original_data);
    printf("Original Length: %u\n\n", original_len);

    // 2. Base64 编码
    printf("--- Encoding process ---\n");

    // 2.1. 计算编码后所需的最大缓冲区大小
    // 使用 bsl_base64.h 中定义的公共宏来安全地计算所需空间
    uint32_t encoded_buffer_size = HITLS_BASE64_ENCODE_LENGTH(original_len);
    char encoded_buffer[encoded_buffer_size];

    // 2.2. 调用编码函数
    uint32_t actual_encoded_len = encoded_buffer_size;
    int32_t result = BSL_BASE64_Encode(original_data, original_len, encoded_buffer, &actual_encoded_len);

    if (result != 0) { // 假设 BSL_SUCCESS 为 0
        printf("Error: BSL_BASE64_Encode failed with code %d\n", result);
        return 1;
    }
    printf("Encoded Data: \"%s\"\n", encoded_buffer);
    printf("Encoded Length: %u\n\n", actual_encoded_len);


    // 3. Base64 解码
    printf("--- Decoding process ---\n");

    // 3.1. 计算解码后所需的最大缓冲区大小
    uint32_t decoded_buffer_size = HITLS_BASE64_DECODE_LENGTH(actual_encoded_len);
    uint8_t decoded_buffer[decoded_buffer_size + 1]; // +1 用于存放字符串结束符 '\0'

    // 3.2. 调用解码函数
    uint32_t actual_decoded_len = decoded_buffer_size;
    result = BSL_BASE64_Decode(encoded_buffer, actual_encoded_len, decoded_buffer, &actual_decoded_len);
    
    if (result != 0) {
        printf("Error: BSL_BASE64_Decode failed with code %d\n", result);
        return 1;
    }
    decoded_buffer[actual_decoded_len] = '\0'; // 手动添加结束符，便于打印
    printf("Decoded Data: \"%s\"\n", decoded_buffer);
    printf("Decoded Length: %u\n\n", actual_decoded_len);

    // 4. 验证结果
    printf("--- Verification ---\n");
    if (original_len == actual_decoded_len && memcmp(original_data, decoded_buffer, original_len) == 0) {
        printf("Success! The decoded data perfectly matches the original data.\n");
    } else {
        printf("Failure! The decoded data does NOT match the original data.\n");
    }
    printf("========================= Test End =========================\n");

    return 0;
}